package com.bytedance.danmaku.render.engine.demo.demo

import android.animation.AnimatorSet
import android.animation.ArgbEvaluator
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.graphics.Color
import android.graphics.PointF
import android.graphics.RectF
import android.graphics.drawable.ColorDrawable
import android.provider.Settings.Global
import android.view.Gravity.NO_GRAVITY
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.bytedance.danmaku.render.engine.DanmakuView
import com.bytedance.danmaku.render.engine.control.DanmakuController
import com.bytedance.danmaku.render.engine.control.DanmakuEvent
import com.bytedance.danmaku.render.engine.control.IEventListener
import com.bytedance.danmaku.render.engine.data.DanmakuData
import com.bytedance.danmaku.render.engine.demo.R
import com.bytedance.danmaku.render.engine.demo.base.BaseDemoActivity
import com.bytedance.danmaku.render.engine.demo.view.ConsoleRecyclerView
import com.bytedance.danmaku.render.engine.render.draw.text.TextData
import com.bytedance.danmaku.render.engine.touch.IItemClickListener
import com.bytedance.danmaku.render.engine.utils.EVENT_DANMAKU_DISMISS
import com.bytedance.danmaku.render.engine.utils.EVENT_DANMAKU_REMEASURE
import com.bytedance.danmaku.render.engine.utils.EVENT_DANMAKU_SHOW
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


/**
 * Created by dss886 on 2021/08/19.
 */
class CmdEventActivity : BaseDemoActivity() {

    private lateinit var mController: DanmakuController
    private lateinit var mConsoleView: ConsoleRecyclerView
    private lateinit var mDanmakuView: DanmakuView
    private lateinit var inflateView: View
    private var mPausingItem: DanmakuData? = null
    private val likeColor = Color.RED
    private val defaultColor = Color.BLUE
    private var isLiked = false
    private lateinit var popupWindow: PopupWindow
    override fun getLayoutId(): Int {
        return R.layout.activity_command_and_event
    }

    override fun init() {
        mConsoleView = findViewById(R.id.console_recycler_view)
        mDanmakuView = findViewById<DanmakuView>(R.id.danmaku_view)
        mController = mDanmakuView.controller
        mController.config.scroll.lineHeight=100f
        mController.config.text.size=60f
        initPopupWindow()
        mController.setData(mDanmakuData)
        mController.addEventListener(object : IEventListener {
            override fun onEvent(event: DanmakuEvent) {
                val eventName = when (event.what) {
                    EVENT_DANMAKU_SHOW -> "Show"
                    EVENT_DANMAKU_DISMISS -> "Dismiss"
                    EVENT_DANMAKU_REMEASURE -> "Re-measure"
                    else -> "Unknown"
                }
                mConsoleView.log("Event", "${eventName}: text=${(event.data as? TextData)?.text}")
            }
        })
        mController.invalidateView()
        mController.itemClickListener = object : IItemClickListener {
            override fun onDanmakuClick(data: DanmakuData, itemRect: RectF, clickPoint: PointF) {
                showPopupWindow(data, itemRect)
                Toast.makeText(
                    this@CmdEventActivity,
                    "Click: text=${(data as? TextData)?.text}",
                    Toast.LENGTH_SHORT
                ).show()
//                mPausingItem = if (mPausingItem == null) {
//                    mController.executeCommand(CMD_PAUSE_ITEM, data)
//                    data.drawOrder = Integer.MAX_VALUE
//                    mConsoleView.log("Cmd", "Pause: text=${(data as? TextData)?.text}")
//                    data
//                } else {
//                    mController.executeCommand(CMD_RESUME_ITEM, mPausingItem)
//                    data.drawOrder = DRAW_ORDER_DEFAULT
//                    mConsoleView.log("Cmd", "Resume: text=${(mPausingItem as? TextData)?.text}")
//                    null
//                }
            }
        }
        mController.start()
    }

    private fun initPopupWindow() {
        popupWindow = PopupWindow(this)
        popupWindow.animationStyle=R.style.PopupAnimation
        inflateView = LayoutInflater.from(this).inflate(R.layout.pop_click_item, null)
        inflateView.findViewById<ImageView>(R.id.link_img).setOnClickListener {
            animateLike(inflateView.findViewById(R.id.link_img))
            isLiked=!isLiked
        }
        popupWindow.contentView = inflateView
        popupWindow.width = WindowManager.LayoutParams.WRAP_CONTENT
        popupWindow.height = WindowManager.LayoutParams.WRAP_CONTENT
        popupWindow.isFocusable = true
        popupWindow.isTouchable = true
        popupWindow.isOutsideTouchable = true
        popupWindow.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
    }
    private fun animateLike(likeIcon: ImageView) {
        // 1. 创建缩放动画（放大后恢复）
        val scaleX = ObjectAnimator.ofFloat(likeIcon, "scaleX", 1f, 1.5f, 1f)
        val scaleY = ObjectAnimator.ofFloat(likeIcon, "scaleY", 1f, 1.5f, 1f)
        scaleX.setDuration(300)
        scaleY.setDuration(300)

        // 2. 创建颜色变化动画
        val startColor: Int = if (isLiked) likeColor else defaultColor
        val endColor: Int = if (isLiked) defaultColor else likeColor

        val colorAnim = ValueAnimator.ofObject(ArgbEvaluator(), startColor, endColor)
        colorAnim.setDuration(300)
        colorAnim.addUpdateListener { animation: ValueAnimator ->
            val color = animation.animatedValue as Int
            likeIcon.setColorFilter(color)
        }

        // 3. 组合动画
        val animatorSet = AnimatorSet()
        animatorSet.playTogether(scaleX, scaleY, colorAnim)
        animatorSet.start()

        // 4. 更新状态
        isLiked = !isLiked
    }
    //todo ：实现点击那条弹幕就显示在覆盖弹幕的位置
//    private fun showPopupWindow(data: DanmakuData,clickRectF: RectF) {
//        val textView=inflateView.findViewById<TextView>(R.id.msg)
//        textView.text=(data as? TextData)?.text+"😁"
//        // 获取弹幕视图在屏幕上的位置
//        val danmakuViewLocation = IntArray(2)
//        mDanmakuView.getLocationOnScreen(danmakuViewLocation)
//
//        // 计算弹幕在屏幕上的位置
//        val danmakuScreenX: Float = danmakuViewLocation[0] + clickRectF.left
//        val danmakuScreenY: Float = danmakuViewLocation[1] + clickRectF.top
//        val danmakuWidth: Float = clickRectF.width()
//        val danmakuHeight: Float = clickRectF.height()
//        // 设置PopupWindow的宽度和高度
////        popupWindow.setWidth(danmakuWidth.toInt())
//        popupWindow.setHeight(danmakuHeight.toInt())
//
//        // 获取屏幕尺寸
//        val screenWidth = resources.displayMetrics.widthPixels
//        val screenHeight = resources.displayMetrics.heightPixels
//
//        // 计算PopupWindow的显示位置
//        var popupX = danmakuScreenX.toInt()
//        var popupY = danmakuScreenY.toInt()
//        // 调整位置，确保PopupWindow不会超出屏幕
//        if (popupX + danmakuWidth > screenWidth) {
////            popupX = (screenWidth - danmakuWidth).toInt();
//            popupX = screenWidth/2
//        }
//
//        if (popupY + danmakuHeight > screenHeight) {
//            popupY = (screenHeight - danmakuHeight).toInt();
//        }
//
//        if (popupX < 0) popupX = 0;
//        if (popupY < 0) popupY = 0;
//        // 显示PopupWindow
//        popupWindow.showAtLocation(mDanmakuView, Gravity.NO_GRAVITY, popupX, popupY);
//    }

    private fun showPopupWindow(data: DanmakuData, clickRectF: RectF) {
        val textView = inflateView.findViewById<TextView>(R.id.msg)
        textView.text = (data as? TextData)?.text + "😁"
        // 获取弹幕视图在屏幕上的位置
        val danmakuViewLocation = IntArray(2)
        mDanmakuView.getLocationOnScreen(danmakuViewLocation)

        // 计算弹幕在屏幕上的位置
        val danmakuScreenX: Float = danmakuViewLocation[0] + clickRectF.left
        val danmakuScreenY: Float = danmakuViewLocation[1] + clickRectF.top
        val danmakuWidth: Float = clickRectF.width()
        val danmakuHeight: Float = clickRectF.height()
        // 设置PopupWindow的宽度和高度
//        popupWindow.setWidth(danmakuWidth.toInt())
        popupWindow.setHeight(danmakuHeight.toInt())

        // 获取屏幕尺寸
        val screenWidth = resources.displayMetrics.widthPixels
        val screenHeight = resources.displayMetrics.heightPixels
        inflateView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
        // 计算PopupWindow的显示位置
        var popupX = (screenWidth-inflateView.measuredWidth)/2
        var popupY = danmakuScreenY.toInt()
        // 调整位置，确保PopupWindow不会超出屏幕
//        if (popupX + danmakuWidth > screenWidth) {

            // 计算水平居中的x坐标（相对于目标视图中心）
//            popupX= (danmakuScreenX + (danmakuWidth - popupWindow.width.toFloat()) / 2).toInt()
//            popupX = (screenWidth - danmakuWidth).toInt();
//            popupX = screenWidth / 2-popupWindow.width/2
//        }

        if (popupY + danmakuHeight > screenHeight) {
            popupY = (screenHeight - danmakuHeight).toInt();
        }

        if (popupX < 0) popupX = 0;
        if (popupY < 0) popupY = 0;
        // 显示PopupWindow
        popupWindow.showAtLocation(mDanmakuView, NO_GRAVITY, popupX, popupY)

        lifecycleScope.launch(Dispatchers.Main) {
            delay(2000)
            if (popupWindow.isShowing)
            popupWindow.dismiss()
        }
    }

    override fun onDestroy() {
        mController.stop()
        super.onDestroy()
    }

}